<script setup lang="ts">
import type { VxeGridInstance, VxeGridProps } from "vxe-table"
import { ElMessage } from "element-plus"
import { onMounted, onUnmounted, reactive, ref, useTemplateRef, watch } from "vue"
import { useRoute } from "vue-router"
import { useApplicationTeacherStore } from "@/pinia/stores/application-teacher"
import { usePositionTeacherStore } from "@/pinia/stores/position-teacher"
import ApplicationDetailDrawer from "./components/ApplicationDetailDrawer.vue"

defineOptions({
  name: "ApplicationTeacherManagement"
})

// #region 响应式数据
const route = useRoute()
const store = useApplicationTeacherStore()
const positionTeacherStore = usePositionTeacherStore()

// 表格引用
const xGridDom = useTemplateRef<VxeGridInstance>("xGridDom")

// 详情抽屉
const detailDrawerVisible = ref(false)
const currentApplicationId = ref(0)

// #region vxe-grid配置
const xGridOpt: VxeGridProps = reactive({
  loading: false,
  autoResize: true,
  pagerConfig: {
    align: "right"
  },
  formConfig: {
    items: [
      {
        field: "studentName",
        itemRender: {
          name: "VxeInput",
          props: {
            placeholder: "学生姓名",
            clearable: true
          },
          events: {
            keyup: (event: KeyboardEvent) => {
              if (event.key === "Enter") {
                xGridDom.value?.commitProxy("query")
              }
            }
          } as { [key: string]: (...args: any[]) => any }
        }
      },
      {
        field: "applicationStatus",
        itemRender: {
          name: "VxeSelect",
          props: {
            placeholder: "申请状态",
            clearable: true,
            options: store.statusOptions
          },
          events: {
            change: () => xGridDom.value?.commitProxy("query")
          } as { [key: string]: (...args: any[]) => any }
        }
      },
      {
        itemRender: {
          name: "VxeButtonGroup",
          options: [
            {
              type: "submit",
              content: "查询",
              status: "primary"
            },
            {
              type: "reset",
              content: "重置",
              events: {
                click: () => {
                  if (xGridDom.value) {
                    // 重置查询参数
                    store.resetQueryParams()
                    xGridDom.value.clearFilter()
                    xGridDom.value.reloadData([])
                    xGridDom.value.commitProxy("query")
                  }
                }
              } as { [key: string]: (...args: any[]) => any }
            }
          ]
        }
      }
    ]
  },
  toolbarConfig: {
    refresh: true
  },
  columns: [
    {
      type: "seq",
      title: "编号",
      width: 80,
      align: "center"
    },
    {
      field: "realName",
      title: "学生姓名",
      minWidth: 120
    },
    {
      field: "politicalStatus",
      title: "政治面貌",
      minWidth: 120
    },
    {
      field: "orgPath",
      title: "组织",
      minWidth: 150
    },
    {
      field: "applicationStatus",
      title: "申请状态",
      minWidth: 120,
      slots: {
        default: "status-column"
      }
    },
    {
      field: "submitTime",
      title: "申请时间",
      minWidth: 180
    },
    {
      field: "resumeUrl",
      title: "简历附件",
      minWidth: 180,
      align: "center",
      slots: {
        default: "resume-column"
      }
    },
    {
      field: "action",
      title: "操作",
      minWidth: 180,
      align: "center",
      slots: {
        default: "action-column"
      }
    }
  ],
  proxyConfig: {
    seq: true,
    form: true,
    autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({ page, form }) => {
        xGridOpt.loading = true
        return new Promise((resolve) => {
          // 更新查询参数
          Object.assign(store.queryParams, {
            studentName: form.studentName || "",
            applicationStatus: form.applicationStatus,
            page: page.currentPage,
            size: page.pageSize
          })

          const callback = () => {
            xGridOpt.loading = false
            resolve({
              total: store.total,
              result: store.applicationList
            })
          }

          store.fetchApplicationList().then(callback).catch(callback)
        })
      }
    }
  }
})
// #endregion

// #region 方法定义
/**
 * 查看申请详情
 */
function handleViewDetail(applicationId: number) {
  currentApplicationId.value = applicationId
  detailDrawerVisible.value = true
}

// 提交审核方法已移至ApplicationDetailDrawer组件内部

/**
 * 查看简历
 */
function handleViewResume(resumeUrl: string) {
  if (resumeUrl) {
    window.open(resumeUrl, "_blank")
  } else {
    ElMessage.warning("简历不存在")
  }
}

// #endregion

// #region 生命周期
onMounted(async () => {
  const positionId = route.query.positionId
  if (positionId) {
    store.setPositionId(Number(positionId))
    // 获取职位详情
    await positionTeacherStore.fetchPositionDetail(Number(positionId))
  }

  // 初始化时获取选项数据
  store.fetchOptions().then(() => {
    // 然后加载申请列表
    if (xGridDom.value) {
      xGridDom.value.commitProxy("query")
    }
  })
})

// 监听路由参数变化
watch(() => route.query.positionId, async (newPositionId) => {
  if (newPositionId) {
    store.setPositionId(Number(newPositionId))
    // 获取职位详情
    await positionTeacherStore.fetchPositionDetail(Number(newPositionId))
    if (xGridDom.value) {
      xGridDom.value.commitProxy("query")
    }
  }
})

// 组件卸载时重置职位详情
onUnmounted(() => {
  positionTeacherStore.resetPositionDetail()
})
// #endregion
</script>

<template>
  <div class="application-management">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>职位申请审核</span>
        </div>
      </template>

      <vxe-grid
        ref="xGridDom"
        v-bind="xGridOpt"
      >
        <!-- 简历列自定义模板 -->
        <template #resume-column="{ row }">
          <template v-if="row.resumeUrl">
            <el-button
              size="small"
              text
              @click="handleViewResume(row.resumeUrl)"
            >
              预览简历
            </el-button>
          </template>
          <span v-else class="text-gray-500">无</span>
        </template>

        <!-- 状态列自定义模板 -->
        <template #status-column="{ row }">
          <el-tag
            :type="row.applicationStatus === 1 ? 'success'
              : row.applicationStatus === 2 ? 'danger'
                : row.applicationStatus === 3 ? 'primary'
                  : row.applicationStatus === 4 ? 'success'
                    : row.applicationStatus === 5 ? 'danger' : 'info'"
          >
            {{ row.applicationStatusName || row.applicationStatus }}
          </el-tag>
        </template>

        <!-- 操作列自定义模板 -->
        <template #action-column="{ row }">
          <el-button-group>
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(row.applicationId)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.applicationStatus === 0 || row.applicationStatus === '0'"
              size="small"
              type="primary"
              @click="handleViewDetail(row.applicationId)"
            >
              审核
            </el-button>
            <el-button
              v-if="row.resumeUrl"
              size="small"
              @click="handleViewResume(row.resumeUrl)"
            >
              查看简历
            </el-button>
          </el-button-group>
        </template>
      </vxe-grid>
    </el-card>

    <!-- 申请详情抽屉 -->
    <ApplicationDetailDrawer
      v-model:visible="detailDrawerVisible"
      :application-id="currentApplicationId"
    />
  </div>
</template>

<style scoped lang="scss">
.application-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.text-gray-500 {
  color: #909399;
}
</style>
